package com.woniuxy.sales.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.woniuxy.sales.common.enumeration.BusinessCode;
import com.woniuxy.sales.model.dto.LoginRequest;
import com.woniuxy.sales.model.entity.Users;
import com.woniuxy.sales.model.vo.ChangePasswordRequest;
import com.woniuxy.sales.service.UsersService;
import com.woniuxy.sales.mapper.UsersMapper;
import com.woniuxy.sales.untils.Assert;
import com.woniuxy.sales.untils.JwtTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Objects;

/**
 * 【用户表】
*/
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users>
    implements UsersService{

    @Autowired
    private UsersMapper usersMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private JwtTemplate jwtTemplate;

    /**
     * 判断邮箱是否存在
     * @param email
     */
    @Override
    public boolean isEmailExist(String email) {
        LambdaQueryWrapper<Users> wrapper= Wrappers.lambdaQuery(Users.class)
                .eq(Users::getEmail,email);
        return usersMapper.selectOne(wrapper) !=null;
    }
    /**
     * 判断用户名是否存在
     * @param username
     */
    @Override
    public boolean isUsernameExist(String username) {
        LambdaQueryWrapper<Users> wrapper=Wrappers.lambdaQuery(Users.class)
                .eq(Users::getUsername,username);
        return usersMapper.selectOne(wrapper)!=null;
    }
    /**
     * 判断电话号码是否存在
     * @param phone
     */
    @Override
    public boolean isPhoneExist(String phone) {
        LambdaQueryWrapper<Users> wrapper=Wrappers.lambdaQuery(Users.class)
                .eq(Users::getPhone,phone);
        return usersMapper.selectOne(wrapper)!=null;
    }
    /**
     * 注册成功，返回新的用户对象
     */
    @Override
    public Users register(Users user) {
        //写入数据库，自动更新user的id值
        usersMapper.insert(user);
        return user;
    }

    /**
     * 验证用户密码
     * @param包含用户token，新旧密码
     */
    @Override
    public void checkPassword(String token, ChangePasswordRequest request) {
        // 根据用户名查找用户
        LambdaQueryWrapper<Users> wrapper = Wrappers.lambdaQuery(Users.class)
                .eq(Users::getUsername, request.getUsername());
        Users user = usersMapper.selectOne(wrapper);

        Assert.error(user == null,BusinessCode.USER_NOT_EXIST);

        Integer userId = Integer.valueOf(jwtTemplate.getValue(token, "userId"));

        Assert.error (userId == null,BusinessCode.INVALID_TOKEN);

        Assert.error(!userId.equals(user.getUserId()), BusinessCode.TOKEN_NOT_EXISTS);

        // 验证旧密码
        Assert.error(!request.getOldPassword().equals(user.getPassword()), BusinessCode.PASSWORD_ERROR);
    }
    /**
     * 修改用户密码
     * @param包含用户token，新旧密码
     */
    @Override
    public void changePassword(ChangePasswordRequest request) {
        // 根据用户名查找用户
        LambdaQueryWrapper<Users> wrapper = Wrappers.lambdaQuery(Users.class)
                .eq(Users::getUsername, request.getUsername());
        Users user = usersMapper.selectOne(wrapper);
        Assert.error(request.getNewPassword().equals(request.getOldPassword()),BusinessCode.NEW_PASSWORD_ERROR);
        // 验证新密码和确认密码是否一致
        Assert.error(!request.getNewPassword().equals(request.getConfirmPassword()), BusinessCode.NEWPASSWORD_ERROR);
        // 更新新密码
        user.setPassword(request.getNewPassword());
        usersMapper.updateById(user);
    }

    @Override
    public Users findById(String token) {
        String userId = jwtTemplate.getValue(token, "userId");
        return usersMapper.selectById(userId);
    }
    /**
     * 用户登录
     */
    @Override
    public ResponseEntity<?> login(LoginRequest param) {
        //获取验证码的key
        String key = param.getKey();
        //得到Redis中验证码
        String code = redisTemplate.opsForValue().get(key);
        //判断验证码是否过期
        if (code == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("验证码已过期");
        }
        //判断验证码是否正确
        if (!code.equalsIgnoreCase(param.getCode())) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("验证码错误");
        }
        //删除Redis中的验证码
        redisTemplate.delete(key);

        //判断用户名是否存在
        LambdaQueryWrapper<Users> wrapper = Wrappers.lambdaQuery(Users.class);
        wrapper.eq(Users::getUsername,param.getUsername());
        Users users = usersMapper.selectOne(wrapper);
        if (Objects.isNull(users)){ //或者user == null
            return ResponseEntity.status(HttpStatus.NOT_FOUND).body("用户不存在");
        }
        //判断密码是否正确
        if (! param.getPassword().equals(users.getPassword())) {
            return ResponseEntity.status(HttpStatus.BAD_REQUEST).body("用户名或者密码不正确");
        }
        //登录成功
        return ResponseEntity.ok(users);
    }

    /**
     * 通过手机号查询用户
     */
    @Override
    public Users findByPhone(String phone) {
        LambdaQueryWrapper<Users> wrapper = Wrappers.lambdaQuery(Users.class).eq(Users::getPhone, phone);
        return usersMapper.selectOne(wrapper);
    }

    @Override
    public Users findByEmail(String email) {
        LambdaQueryWrapper<Users> wrapper = Wrappers.lambdaQuery(Users.class).eq(Users::getEmail, email);
        return usersMapper.selectOne(wrapper);
    }

    @Override
    public void updateUserInfo(LoginRequest loginRequest) {
            // 根据用户id查找用户
        LambdaQueryWrapper<Users> wrapper = Wrappers.lambdaQuery(Users.class)
                .eq(Users::getUserId, loginRequest.getUserId());
        Users user = usersMapper.selectOne(wrapper);

        // 验证用户名是否重复，排除当前用户
        LambdaQueryWrapper<Users> usernameWrapper = Wrappers.lambdaQuery(Users.class)
                .eq(Users::getUsername, loginRequest.getUsername())
                .ne(Users::getUserId, loginRequest.getUserId()); // 排除当前用户
        Users existingUsernameUser = usersMapper.selectOne(usernameWrapper);
        Assert.error(existingUsernameUser != null, BusinessCode.USER_IS_EXIST);

        // 验证邮箱是否重复，排除当前用户
        LambdaQueryWrapper<Users> emailWrapper = Wrappers.lambdaQuery(Users.class)
                .eq(Users::getEmail, loginRequest.getEmail())
                .ne(Users::getUserId, loginRequest.getUserId()); // 排除当前用户
        Users existingEmailUser = usersMapper.selectOne(emailWrapper);
        Assert.error(existingEmailUser != null, BusinessCode.EMAIL_EXIST_ERROR);

        // 验证手机号是否重复，排除当前用户
        LambdaQueryWrapper<Users> phoneWrapper = Wrappers.lambdaQuery(Users.class)
                .eq(Users::getPhone, loginRequest.getPhone())
                .ne(Users::getUserId, loginRequest.getUserId()); // 排除当前用户
        Users existingPhoneUser = usersMapper.selectOne(phoneWrapper);
        Assert.error(existingPhoneUser != null, BusinessCode.PHONE_IS_EXIST);

        // 更新用户信息
        user.setUsername(loginRequest.getUsername());
        user.setEmail(loginRequest.getEmail());
        user.setPhone(loginRequest.getPhone());
        usersMapper.updateById(user);
    }

}




